package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @Description RoleServiceImpl
 * @Author Wen Jie
 * @Date 2024-09-16
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Override
    public PageResponse<RoleVo> findRolePage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Role> roles = roleMapper.list(roleDto);
        PageResponse<RoleVo> pageResponse = PageResponse.of(roles, RoleVo.class);
        return pageResponse;
    }

    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleMapper.findCheckedResources(roleId);
    }

    @Override
    public Boolean updateRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        //如果资源列表为空直接返回
        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            return true;
        }
        //不为空则先删除
        roleResourceMapper.deleteRoleResourceByRoleId(roleDto.getId());
        //批量新增角色资源信息
        List<RoleResource> roleResourceList = new ArrayList<>();
        String[] resourceNos = roleDto.getCheckedResourceNos();
        List<String> resourceNoList = Arrays.asList(resourceNos);
        resourceNoList.forEach(
                resourceNo -> {
                    RoleResource roleResource = RoleResource.builder().roleId(roleDto.getId())
                            .resourceNo(resourceNo)
                            .dataState(SuperConstant.DATA_STATE_0)
                            .build();
                    roleResourceList.add(roleResource);
                }
        );
        roleResourceMapper.batchInsert(roleResourceList);
        return true;
    }

    @Override
    public void deleteRole(Long roleId) {
        //先删除角色资源信息
        roleResourceMapper.deleteRoleResourceByRoleId(roleId);
        //再删除角色信息
        roleMapper.deleteByPrimaryKey(roleId);
    }
}
